<template>
  <div class="dashboard-container">
    <div class="app-container">
      <HeadTool :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push({ path: '/improt', query: { type: 'com' } })"
                   :disabled='!checkPermission("dr")'
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
                 :disabled='!checkPermission("dc")'
            >导出</el-button
          >
          <el-button size="small" type="primary" @click="showDialog = true"
                 :disabled='!checkPermission("add")'
            >新增员工</el-button
          >
        </template>
      </HeadTool>
      <!-- 放置表格和分页 -->
      <el-card style="width: 100%">
        <el-table border :data="list" style="width: 100%">
          <el-table-column width="120" type="index" label="序号" sortable="" />
          <el-table-column
            width="120"
            prop="username"
            label="姓名"
            sortable=""
          />
          <el-table-column width="70" prop="staffPhoto" label="头像">
            <template slot-scope="{ row }">
              <img
                style="
                  display: block;
                  margin: 0 auto;
                  width: 40px;
                  heigth: 40px;
                "
                :src="row.staffPhoto"
                v-imageerror="isstaffPhoto"
                @click="erweima(row.staffPhoto)"
                alt=""
              />
            </template>
          </el-table-column>

          <el-table-column
            width="120"
            prop="mobile"
            label="手机号"
            sortable=""
          />
          <el-table-column
            width="120"
            prop="workNumber"
            label="工号"
            sortable=""
          />
          <el-table-column
            width="120"
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
          >
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            prop="departmentName"
            label="部门"
            sortable=""
          />
          <el-table-column
            width="120"
            prop="timeOfEntry"
            label="入职日期"
            sortable=""
          >
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            prop="correctionTime"
            label="转正日期"
            sortable=""
          >
            <template slot-scope="{ row }">
              {{ row.correctionTime | formatDate}}
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            prop="enableState"
            label="是否在职"
            sortable=""
          >
            <template slot-scope="{ row }">
              {{ row.enableState | enableState }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="状态">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="操作"
            sortable=""
            fixed="right"
            width="280"
          >
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                :disabled='!checkPermission("bj")'
                @click="$router.push(`/employees/detail/${row.id}`)"
                >编辑</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                       :disabled='!checkPermission("js")'
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                     :disabled='!checkPermission("del")'
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            :page-size="page.size"
            :current-page="page.page"
            layout="total,prev, pager, next"
            :total="page.total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <add-employee :showDialog.sync="showDialog"></add-employee>
      <assign-role
        ref="assignRole"
        :showAssign.sync="showAssign"
        :user-id="userId"
      ></assign-role>
      <!-- 二维码 -->
      <el-dialog
        title="二维码"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
      >
        <el-row type="flex" justify="center">
          <canvas ref="canVas"></canvas>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import addEmployee from "./components/add-employee.vue";
import { getEmployeeList, delEmployee } from "@/api/employees.js";
import constant from "@/api/constant/employees";
import QrCode from "qrcode";
// 导入处理日期的函数
import { formatDate } from "@/filters";
import AssignRole from "./components/assign-role.vue";
export default {
  name: "com",
  data() {
    return {
      jsq: 0,
      // 二维码
      centerDialogVisible: false,
      // 新增窗口
      showDialog: false,
      // 角色窗口
      showAssign: false,
      // 头像
      isstaffPhoto: require("@/assets/common/bigUserHeader.png"),
      userId: "",
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
    };
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      let res = await getEmployeeList(this.page);
      this.list = res.rows;
      // 因为el-switch接收的是一个布尔类型
      // 而enableState是数字类型，所以我们拿到数据后需要先转成布尔类型
      this.list.forEach((item) => {
        item.enableState = item.enableState == 1 ? true : false;
      });

      this.page.total = res.total;
    },
    // 分页点击事件
    currentChange(newPage) {
      this.page.page = newPage;
      this.getEmployeeList();
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm("确定删除该员工吗？", "温馨提示");
        await delEmployee(id);
        this.list.length == 1 && this.page.page != 1 ? this.page.page-- : "";
        this.getEmployeeList();
        this.$message.success("删除员工成功");
      } catch (err) {}
    },
    // 角色管理
    async editRole(id) {
      this.userId = id;
      await this.$refs.assignRole.getUserInfotx(id); // 父组件调用子组件方法
      this.showAssign = true;
    },
    // 显示二维码
    erweima(url) {
      if (url) {
        this.centerDialogVisible = true;
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.canVas, url);
        });
      } else {
        let item = Date.now();
        if (item - this.jsq > 500) {
          this.$message.warning("该用户还未上传头像!");
          this.jsq = Date.now();
        }
      }
    },
    // 导出Excel
    async exportData() {
      try {
        await this.$confirm("确定要导出所有员工吗？", "温馨提示");
        let { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        const headers = {
          手机号: "mobile",
          姓名: "username",
          入职日期: "timeOfEntry",
          聘用形式: "formOfEmployment",
          转正日期: "correctionTime",
          工号: "workNumber",
          部门: "departmentName",
        };
        let keys = Object.keys(headers);
        let bigArr = rows.map((item) => {
          let arr = [];
          for (let key in headers) {
            if (key == "入职日期" || key == "转正日期") {
              let res = formatDate(item[headers[key]]);
              arr.push(res);
            } else if (key == "聘用形式") {
              let str = item[headers[key]] == 1 ? "正式" : "临时工";
              arr.push(str);
            } else {
              arr.push(item[headers[key]]);
            }
          }
          return arr;
        });

        import("@/vendor/Export2Excel").then((excel) => {
          excel.export_json_to_excel({
            header: keys, //表头 必填
            data: bigArr, //具体数据 必填
            filename: "员工列表", //非必填
            // autoWidth: true, //非必填
            // bookType: "xlsx", //非必填
          });
        });
      } catch (err) {
        console.log(err);
      }
    },
  },
  components: {
    addEmployee,
    AssignRole,
  },
  filters: {
    formatHireType(val) {
      let list = constant.hireType.filter((item) => item.id == val);

      return list[0] ? list[0].value : "未知";
    },
    enableState(val) {
      return val == 1 ? "在职" : "离职";
    },
  },
  created() {
    this.getEmployeeList();
  },
};
</script>

<style>


</style>
